#ifndef __PROCESS_POOL_HPP__
#define __PROCESS_POOL_HPP__

#include <iostream>
#include <vector>
#include <string>
#include <sys/types.h>
#include<sys/wait.h>
#include <unistd.h>
#include"task.hpp"

//先描述
class Channel
{
public:
    Channel(int wfd, pid_t id)
        : _wfd(wfd), _pid(id)
    {
        _name = "channel-" + std::to_string(_wfd) + "-" + std::to_string(_pid);
    }
    ~Channel()
    {
    }

    void Send(int taskcode)
    {
        ssize_t n=write(_wfd,&taskcode,sizeof(taskcode));
    }

    void Close()
    {
        //根据管道通信的原理，只要关闭父进程写端，对应子进程read返回0,然后设置判断条件关闭
        close(_wfd);
    }

    void Wait()
    {
        pid_t pid=waitpid(_pid,nullptr,0);
        std::cout<<"等待子进程："<<std::to_string(_pid)<<"成功"<<std::endl;
    }

    int Fd() { return _wfd; }

    pid_t Pid() { return _pid; }

    std::string Name() { return _name; }

private:
    int _wfd;
    pid_t _pid;
    std::string _name;
};

//再组织
class ChannelManager
{
public:
    ChannelManager():_next(0)
    {
    }
    ~ChannelManager()
    {
    }

    Channel& Select()
    {
        //通过_next实现轮询
        auto&c=_channels[_next];
        _next++;
        _next%=_channels.size();
        return c;
    }

    void InsertChannel(int wfd, pid_t id)
    {
        _channels.emplace_back(wfd, id);
        // _channels.push_back({wfd,id});  先构造后移动
    }

    void PrintChannels()
    {
        for (auto &c : _channels)
        {
            std::cout << c.Name() << std::endl;
        }
    }
    void CloseAllWfd()
    {
        //创建子进程时关闭与子进程无关的写端
        for(auto&c:_channels)
        {
            c.Close();
        }
    }

    void CloseSubProcess()
    {
        for(auto&c:_channels)
        {
            c.Close();
        }
    }

    void WaitSubProcess()
    {
        for(auto&c:_channels)
        {
            c.Wait();
        }
    }

    void CloseAndWait()
    {
        //解决方法1.倒着关闭
        // for(int i=_channels.size()-1;i>=0;i--)
        // {
        //     _channels[i].Close();
        //     _channels[i].Wait();
        // }

        //2.让子进程关闭其它进程的w端
        for(auto &c:_channels)
        {
            c.Close();
            c.Wait();
        }

    }

private:
    std::vector<Channel> _channels;
    int _next;
};

const int gdefaultnum = 5;

class ProcessPool
{
public:
    ProcessPool(int n=gdefaultnum) : _process_num(n)
    {
        _tm.Register(PrintLog);
        _tm.Register(Download);
        _tm.Register(Upload);
    }
    ~ProcessPool()
    {
    }

    void Work(int rfd, pid_t id)
    {
        while (true)
        {
            int code = 0;
            ssize_t n = read(rfd, &code, sizeof(code));
            if (n > 0)
            {
                if (n != sizeof(code))
                {
                    // 读取的数据不规范，无效
                    continue;
                }
                std::cout<<"子进程["<<getpid()<<"]收到一个任务码："<<std::to_string(code)<<std::endl;
                _tm.Execute(code);
                std::cout<<"++++++++++++++++++++++++++++"<<std::endl;
            }
            else if (n == 0)
            {
                std::cout << "写端已关闭，子进程退出，该信道关闭" << std::endl;
                break;
            }
            else
            {
                std::cerr << "读取错误" << std::endl;
                break;
            }
        }
    }

    bool Creat()
    {
        for (int i = 0; i < _process_num; i++)
        {
            int fds[2] = {0};
            // 1.创建管道
            int n = pipe(fds);
            if (n < 0)
                return false;

            // 2.创建子进程
            pid_t subid = fork();
            if (subid < 0)
                return false;
            else if (subid == 0)
            {
                // 关闭所有继承的无关写端
                _cm.CloseAllWfd();
                //关闭自己管道的写端
                close(fds[1]);

                Work(fds[0], subid);

                close(fds[0]);
                exit(0);
            }
            else
            {
                // 关闭读端
                close(fds[0]);
                _cm.InsertChannel(fds[1], subid);
            }
        }
        return true;
    }

    void Run()
    {
        //1.生成任务码
        int taskcode=_tm.Code();
        //2.选择一个子进程
        auto& c=_cm.Select();
        std::cout<<"选择了一个信道"<<c.Name()<<std::endl;
        //3.发送任务码
        c.Send(taskcode);
        std::cout<<"发送了一个任务码："<<std::to_string(taskcode)<<std::endl;
    }

    void Stop()
    {
        // //关闭所有子进程
        // _cm.CloseSubProcess();
        // //等待所有子进程
        // _cm.WaitSubProcess();

        _cm.CloseAndWait();
    }

    void Debug()
    {
        _cm.PrintChannels();
    }

private:
    int _process_num;
    ChannelManager _cm;
    TaskManager _tm;
};

#endif